package secret.hehe.com.secret.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.net.URLEncoder;

import secret.hehe.com.secret.R;
import secret.hehe.com.secret.Util.Util;

import static secret.hehe.com.secret.Util.Util.changeImg;
import static secret.hehe.com.secret.Util.Util.doDelete;
import static secret.hehe.com.secret.Util.Util.doInsert;
import static secret.hehe.com.secret.Util.Util.doSelect;
import static secret.hehe.com.secret.Util.Util.doUpdate;

/**
 * Created by DELL on 2018/2/28.
 */

public class AddContactActivity extends AppCompatActivity {
    private String aid;//通讯录id
    private String sendId;//本人id
    private String recvId;//对方id
    private String nickname;//昵称
    private int isUpdate=0;//判断是否为更新
    private int icon;//头像编号
    private ImageView imageView;//对方头像
    private EditText ID;//对方id编辑框
    private EditText name;//对方昵称编辑框
    private Button delete;//删除按钮
    private int canClick=1;//限制按钮点击次数
    private String jsonString;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcontact);

        //接受数据
        Intent intent = getIntent();
        imageView = (ImageView) findViewById(R.id.contactHead);
        ID = (EditText)findViewById(R.id.contact_user_text);
        name = (EditText)findViewById(R.id.contact_name_text);
        //接收数据
        try {
            //sendID为自己，recvID为对方
            //出错时为添加联系人
            sendId=(String) intent.getSerializableExtra("sendId");
            recvId=(String) intent.getSerializableExtra("recvId");
            ID.setText(recvId);
            aid = (String) intent.getSerializableExtra("aid");
            isUpdate =(int) intent.getSerializableExtra("isUpdate");
            nickname = (String) intent.getSerializableExtra("name");
            icon =(int) intent.getSerializableExtra("icon");
            name.setText(nickname);
        }catch (Exception e){
            e.printStackTrace();
        }
        //防止变量杀死
        if (savedInstanceState != null) {
            try {
                sendId=savedInstanceState.getString("sendId");
                recvId=savedInstanceState.getString("recvId");
                ID.setText(recvId);
                aid = savedInstanceState.getString("aid");
                isUpdate =savedInstanceState.getInt("isUpdate");
                nickname = savedInstanceState.getString("name");
                icon = savedInstanceState.getInt("icon");
                canClick = savedInstanceState.getInt("canClick");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        changeImg(icon,imageView,getApplicationContext());

        delete = (Button)findViewById(R.id.contact_delect_button);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(canClick==1){
                    canClick=0;
                    new AlertDialog.Builder(AddContactActivity.this).setTitle("提示")
                            .setMessage("确定要删除?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Util util = new Util();
                                    String params = "user1="+sendId
                                            +"&user2="+URLEncoder.encode(ID.getText().toString());
                                    Util.postThread deleteThread = util.new postThread("/user/delAddress",getApplicationContext(),params,handler,3);
                                    deleteThread.start();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            return;
                        }
                    }).show();
                }
                else return;
            }
        });
        //判定是否为修改
        if(isUpdate==1){
            ID.setEnabled(false);
        }else{
            delete.setVisibility(View.INVISIBLE);
        }

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_addcontact, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
            case R.id.address_finish: {
                if (canClick == 1) {
                    canClick = 0;
                    if(ID.getText().toString().equals(sendId)){
                        new AlertDialog.Builder(AddContactActivity.this).setTitle("提示")//设置对话框标题
                                .setMessage("不能添加自己为联系人")//设置显示的内容
                                .show();
                        return true;
                    }
                    new AlertDialog.Builder(AddContactActivity.this).setTitle("提示")
                            .setMessage("确定要保存?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Util util = new Util();
                                    String params = "user1="+sendId
                                            +"&user2="+URLEncoder.encode(ID.getText().toString())
                                            +"&data[user1]="+sendId
                                            +"&data[user2]="+URLEncoder.encode(ID.getText().toString())
                                            +"&data[nickname]="+URLEncoder.encode(name.getText().toString())
                                            +"&data[isscreen]=0"
                                            +"&data[keyhead]=123";
                                    if(isUpdate==0){
                                        //添加联系人
                                        Util.postThread registerThread = util.new postThread("/user/addAddress",getApplicationContext(),params,handler,1);
                                        registerThread.start();
                                    }else{
                                        //修改联系人
                                        if(name.getText().toString().equals(nickname)){
                                            Toast.makeText(AddContactActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                            finish();
                                        }else{
                                            Util.postThread registerThread = util.new postThread("/user/updateAddress",getApplicationContext(),params,handler,2);
                                            registerThread.start();
                                        }

                                    }
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            return;
                        }
                    }).show();

                }
                return true;
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //保存变量
        super.onSaveInstanceState(outState);
        outState.putString("sendId", sendId);
        outState.putString("recvId", recvId);
        outState.putString("aid", aid);
        outState.putInt("isUpdate", isUpdate);
        outState.putString("name", nickname);
        outState.putInt("icon", icon);
        outState.putInt("canClick", canClick);
    }

    Handler handler = new Handler() {
        //相应接受数据
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                canClick=1;
                //添加通讯录响应
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    if(code==200){//添加成功
                        JSONObject data = new JSONObject(jsonObject.getString("data"));
                        Toast.makeText(AddContactActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                        JSONArray addressData = new JSONArray();
                        addressData.put(data);
                        doInsert("address",addressData,getApplicationContext());

                        JSONObject friend = new JSONObject();
                        friend.put("id",URLEncoder.encode(ID.getText().toString()));
                        friend.put("pwd","");
                        friend.put("icon",icon);
                        JSONArray friendData = new JSONArray();
                        friendData.put(friend);
                        doInsert("user",friendData,getApplicationContext());
                        //String where1 = "a.user1="+sendId+" and a.user2=u.id and a.isscreen=0";
                        //String addressResult="{\"data\":"+doSelect("user u,address a",where1,getApplicationContext())+"}";
                        Intent intent = new Intent();
                        setResult(1000, intent);
                        finish();
                    }else if(code==222){
                        Toast.makeText(AddContactActivity.this, "联系人账户不存在", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(AddContactActivity.this, "该联系人早已保存", Toast.LENGTH_SHORT).show();
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 2) {
                //修改通讯录响应
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    JSONObject data = new JSONObject(jsonObject.getString("data"));
                    int code = jsonObject.getInt("code");
                    if(code==200){//修改成功
                        Toast.makeText(AddContactActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        JSONArray jsonArray = new JSONArray();
                        jsonArray.put(data);
                        doUpdate("address",jsonArray,getApplicationContext());
                        //String where1 = "a.user1="+sendId+" and a.user2=u.id and a.isscreen=0";
                        //String addressResult="{\"data\":"+doSelect("user u,address a",where1,getApplicationContext())+"}";
                        Intent intent = new Intent();
                        setResult(1000, intent);
                        finish();
                    }else if(code==201){
                        Toast.makeText(AddContactActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                    }
                    canClick=1;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 3) {
                //删除通讯录响应
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    if(code==200){//修改成功
                        Toast.makeText(AddContactActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        String where = "aid="+aid;
                        doDelete("address",where,getApplicationContext());
                        //String where1 = "a.user1="+sendId+" and a.user2=u.id and a.isscreen=0";
                        //String addressResult="{\"data\":"+doSelect("user u,address a",where1,getApplicationContext())+"}";
                        Intent intent = new Intent();
                        setResult(1000, intent);
                        finish();
                    }else if(code==201){
                        Toast.makeText(AddContactActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                    canClick=1;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 0) {
                canClick=1;
                Toast.makeText(AddContactActivity.this, "无网络或访问服务器出错", Toast.LENGTH_SHORT).show();
            }
        }
    };

}
